package com.nti56.springboot.service;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.nti56.springboot.model.Organization;
import com.nti56.springboot.model.TreeNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nti56.springboot.cache.BaseDataCache;
import com.nti56.springboot.exception.MyRuntimeException;
import com.nti56.springboot.mapper.tmsmapper.OrganizationMapper;

import com.nti56.springboot.utils.ParamUtil;
import com.nti56.springboot.utils.TreeNodeUtil;
@Service
public class OrganizationService {
	
	private static final Logger logger = LoggerFactory.getLogger(OrganizationService.class);

	
	
	@Autowired
	private OrganizationMapper organizationMapper;
	
	@Autowired
	private BaseDataCache baseDataCache;
	
	public void refreshCache() {
		List<Organization> orgList = this.getAllOrganization(null);
		List<TreeNode> orgTreeNodeList = this.getAllOrganizationTreeData(null);
		baseDataCache.putOrganizations(orgList);
		baseDataCache.putTreeNode4Org(orgTreeNodeList);
	}
	
	public boolean checkExist(String deptCode) {
		Long cnt = organizationMapper.countByMap(ParamUtil.setParam("deptCode", deptCode));
		if(cnt >0) {
			return true;
		}else {
			return false;
		}
	}
	
	/**
	 * @param org
	 */
	@Transactional(rollbackFor = Exception.class, transactionManager = "tmsTransactionManager")
	public void insert(Organization org) {
		boolean exist = this.checkExist(org.getDeptCode());
		if(exist) {
			throw new MyRuntimeException("组织机构编码:"+org.getDeptCode()+" 已经存在请勿重复添加!");
		}else {
			organizationMapper.insert(org);
		}
	}
	
	@Transactional(rollbackFor = Exception.class, transactionManager = "tmsTransactionManager")
	public void update(Organization org) {
		Long cnt = organizationMapper.countByMap(ParamUtil.setParam("orgIdNotEq", org.getOrgId())
				.setParam("deptCode", org.getDeptCode()));
		if(cnt>0) {
			throw new MyRuntimeException("组织机构编码:"+org.getDeptCode()+" 已经存在请勿重复修改!");
		}else {
			organizationMapper.update(org);
		}
	}
	
	@Transactional(rollbackFor = Exception.class, transactionManager = "tmsTransactionManager")
	public void delete(String orgId) {
		organizationMapper.delete(orgId);
	}
	
	public Organization getOrganizationById(String id) {
		return organizationMapper.getById(id);
	}
	
	
	public List<Organization> getAllOrganization(Map conditions){
		return organizationMapper.findAll(conditions);
	}
	
	
	/**
	 * 根据父节点ID 获取所有子节点的组织机构编码(包含自身)
	 * @param pId
	 * @return
	 */
	public List<String> getSubOrgCodes(String pId){
		List<Organization> orgList = this.baseDataCache.getOrganizations();
		List<TreeNode> nodeList = Organization.orgList2SimpleNodeList(orgList);
		List<TreeNode> children = new ArrayList<TreeNode>();
		TreeNodeUtil.getSimpleChilds(children,nodeList,pId);
		Organization org = this.getByIdFromCache(pId);
		String pOrgCode = org.getDeptCode();
		List<String> orgCodes = new ArrayList<String>();
		orgCodes.add(pOrgCode);
		for(TreeNode tn : children) {
			orgCodes.add(tn.getAttributes().get("deptCode").toString());
		}
		return orgCodes;
	}
	
	
	
	private Organization getByIdFromCache(String id) {
		List<Organization> orgList = this.baseDataCache.getOrganizations();
		for(Organization org : orgList) {
			if(id.equals(org.getOrgId())) {
				return org;
			}
		}
		return null;
	}
	
	public List<TreeNode> getAllOrganizationTreeData(Map conditions){
		List<TreeNode> treeList = new ArrayList<TreeNode>();
		List<TreeNode> nodeList = new ArrayList<TreeNode>();
		try {
			List<Organization> list = organizationMapper.findAll(conditions);
			for (Organization org : list) {
				TreeNode tree = new TreeNode();
				tree.setId(org.getOrgId());
				tree.setpId(org.getParentId());
				tree.setText(org.getDeptName());
				tree.setChecked(org.isChecked());
				tree.setState(org.getState());
				tree.setChildren(org.getChildren());
				//设置树控件attributes属性的数据				
				Map<String, Object> attributes = TreeNodeUtil.getAttributes(org);
                tree.setAttributes(attributes);				
				nodeList.add(tree);
			}
			treeList = TreeNodeUtil.getFatherNode(nodeList);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		return treeList;
	}
	
	
}
